#!/usr/bin/python3
# -*- coding: UTF-8 -*- 
"""
output funclist in YOUR_APP.s
    objdump -d YOUR_APP > YOUR_APP.s
    python3 output_fun_sort.py -i YOUR_APP.s -l c/c++
"""

import re
import os
import stat
import argparse

def get_func_list(args):
    """
    get a list of funcs from input_file
    """
    input_file=args.input_file
    print("input_file: {}".format(input_file))

    with open(input_file,"r") as file:
        func_record=0
        call_record=0
        func_base_addr=None
        for line in file.readlines():
            line=line.strip()
            caller=None

            if re.match(r'Disassembly of section \.text',line):
                call_record=1
                continue
            if re.match(r'Disassembly of section',line) and call_record==1:
                break

            if call_record==1:
                result=re.match(r'^([0-9a-f]+)\s+<(.*)>:$',line)

                if result is not None:
                    caller=result.group(2)
                    func_base_addr=result.group(1)
                    print("{}".format(line))
                    continue

                if re.match(r'\s*$',line):
                    func_record=0

                is_instruct=re.match(r'^\s*([0-9a-f]+)\:.*',line)

                if is_instruct is not None:
                    instruct_addr=is_instruct.group(1)

                    if instruct_addr is not None and func_base_addr is not None:
                        new_addr=int(instruct_addr, 16) - int(func_base_addr, 16)
                        new_line="{:>4d} {} {}".format(new_addr, hex(new_addr), line)

                        print("{}".format(new_line))
                        continue

            print("{}".format(line))

        return None

def defin_and_parse_args():
    parser=argparse.ArgumentParser(description="func tool for asm")
    parser.add_argument('-i','--input_file',type=str,help='input file witch asm need to be parsed',required=True)

    return parser.parse_args()

def main():
    args=defin_and_parse_args()
    get_func_list(args)

if __name__=='__main__':
    main()



                
        
